import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Progress } from '@/components/ui/progress';
import { useVocabulary } from '@/contexts/VocabularyContext';
import { selectRandomWords, getWordCountByDifficulty } from '@/utils/gameHelpers';
import { ArrowLeft, Trophy, CheckCircle, XCircle } from 'lucide-react';
import type { Category, Word } from '@/types/vocabulary';

const SpellingGame: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { getWordsByCategory, settings, updateSpellingStats, updateCategoryStats } = useVocabulary();
  const category = (location.state?.category as Category) || '全部类别';

  const [words, setWords] = useState<Word[]>([]);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [userInput, setUserInput] = useState('');
  const [feedback, setFeedback] = useState<'correct' | 'wrong' | null>(null);
  const [correctCount, setCorrectCount] = useState(0);
  const [wrongWords, setWrongWords] = useState<Word[]>([]);
  const [isGameComplete, setIsGameComplete] = useState(false);

  useEffect(() => {
    initializeGame();
  }, []);

  const initializeGame = () => {
    const allWords = getWordsByCategory(category);
    const wordCount = getWordCountByDifficulty(settings.difficulty);
    const selectedWords = selectRandomWords(allWords, wordCount);
    setWords(selectedWords);
    setCurrentIndex(0);
    setCorrectCount(0);
    setWrongWords([]);
    setIsGameComplete(false);
    setUserInput('');
    setFeedback(null);
  };

  const handleCheck = () => {
    const currentWord = words[currentIndex];
    const isCorrect = userInput.trim().toLowerCase() === currentWord.english.toLowerCase();

    setFeedback(isCorrect ? 'correct' : 'wrong');
    updateCategoryStats(currentWord.category, isCorrect);

    if (isCorrect) {
      setCorrectCount((prev) => prev + 1);
    } else {
      setWrongWords((prev) => [...prev, currentWord]);
    }

    setTimeout(() => {
      if (currentIndex + 1 < words.length) {
        setCurrentIndex((prev) => prev + 1);
        setUserInput('');
        setFeedback(null);
      } else {
        setIsGameComplete(true);
        updateSpellingStats(words.length, correctCount + (isCorrect ? 1 : 0));
      }
    }, 1500);
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && userInput.trim() && !feedback) {
      handleCheck();
    }
  };

  if (words.length === 0) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50 flex items-center justify-center">
        <div className="text-center">
          <p className="text-xl text-gray-600">加载中...</p>
        </div>
      </div>
    );
  }

  const progress = words.length > 0 ? ((currentIndex + 1) / words.length) * 100 : 0;
  const accuracy = words.length > 0 ? Math.round((correctCount / words.length) * 100) : 0;

  if (isGameComplete) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50 flex items-center justify-center p-4">
        <Card className="max-w-2xl w-full">
          <CardContent className="pt-6">
            <div className="text-center space-y-6">
              <Trophy className="w-20 h-20 text-yellow-500 mx-auto" />
              <h2 className="text-3xl font-bold text-gray-900">练习完成！</h2>
              <div className="space-y-3">
                <div className="flex items-center justify-between text-lg">
                  <span className="text-gray-600">正确数量：</span>
                  <span className="font-semibold text-green-600">{correctCount}</span>
                </div>
                <div className="flex items-center justify-between text-lg">
                  <span className="text-gray-600">错误数量：</span>
                  <span className="font-semibold text-red-600">{wrongWords.length}</span>
                </div>
                <div className="flex items-center justify-between text-lg">
                  <span className="text-gray-600">准确率：</span>
                  <span className="font-semibold">{accuracy}%</span>
                </div>
              </div>

              {wrongWords.length > 0 && (
                <div className="mt-6 text-left">
                  <h3 className="font-semibold text-lg mb-3">需要复习的单词：</h3>
                  <div className="space-y-2 max-h-48 overflow-y-auto">
                    {wrongWords.map((word) => (
                      <div
                        key={word.id}
                        className="flex justify-between items-center p-3 bg-red-50 rounded-lg"
                      >
                        <span className="font-semibold">{word.english}</span>
                        <span className="text-gray-600">{word.chinese}</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              <div className="flex gap-3 mt-6">
                <Button onClick={() => navigate('/')} variant="outline" className="flex-1">
                  返回首页
                </Button>
                <Button onClick={initializeGame} className="flex-1">
                  再练一次
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  const currentWord = words[currentIndex];

  return (
    <div className="min-h-screen bg-gray-100 p-4">
      <div className="container mx-auto max-w-3xl">
        {/* 顶部导航栏 */}
        <div className="flex items-center justify-between mb-8">
          <Button variant="ghost" onClick={() => navigate('/')} className="bg-white hover:bg-gray-50">
            <ArrowLeft className="w-4 h-4 mr-2" />
            返回
          </Button>
          <div className="flex items-center gap-8">
            <div className="text-lg font-semibold">
              进度: {currentIndex + 1}/{words.length}
            </div>
            <div className="text-lg font-semibold">
              得分: {correctCount * 10}
            </div>
          </div>
        </div>

        {/* 游戏标题和说明 */}
        <div className="text-center mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-3">拼写练习游戏</h1>
          <p className="text-gray-600 mb-2">根据中文提示，正确拼写出英文单词。</p>
          <p className="text-sm text-gray-500">注意：单词拼写区分大小写，请使用小写字母。</p>
        </div>

        {/* 进度条 */}
        <div className="mb-8">
          <Progress value={progress} className="h-3 bg-gray-200" />
        </div>

        {/* 中文提示 */}
        <div className="text-center mb-8">
          <p className="text-5xl font-bold text-gray-900">{currentWord.chinese}</p>
        </div>

        {/* 输入区域 */}
        <div className="max-w-xl mx-auto space-y-4">
          <Input
            type="text"
            value={userInput}
            onChange={(e) => setUserInput(e.target.value)}
            onKeyPress={handleKeyPress}
            placeholder="请输入英文单词..."
            className="text-xl text-center py-6 border-2 border-purple-300 focus:border-purple-500"
            disabled={!!feedback}
            autoFocus
          />

          {feedback && (
            <div
              className={`flex items-center justify-center gap-2 p-4 rounded-lg ${
                feedback === 'correct' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
              }`}
            >
              {feedback === 'correct' ? (
                <>
                  <CheckCircle className="w-6 h-6" />
                  <span className="font-semibold text-lg">正确！</span>
                </>
              ) : (
                <>
                  <XCircle className="w-6 h-6" />
                  <span className="font-semibold text-lg">
                    错误！正确答案是: {currentWord.english}
                  </span>
                </>
              )}
            </div>
          )}

          <Button
            onClick={handleCheck}
            disabled={!userInput.trim() || !!feedback}
            className="w-full py-6 text-lg bg-purple-600 hover:bg-purple-700 text-white"
            size="lg"
          >
            检查答案
          </Button>
        </div>
      </div>
    </div>
  );
};

export default SpellingGame;
